<style lang="stylus" scoped>

</style>

<template>
  <div>
    <div :style="{ color: errorCopy ? '#c10015': '' }">{{ fieldName }}</div>
    <q-input
      v-model="labelCopy"
      dense readonly borderless
      :style="{ borderBottom: errorCopy ? '1px solid #c10015': '1px solid #ccc' }"
    >
      <template v-slot:append>
        <q-icon :name="toggleCopy?'arrow_drop_up': 'arrow_drop_down'" class="cursor-pointer" />
      </template>
    </q-input>
    <p v-if="errorCopy" class="text-negative">该字段为必填项</p>
    <q-popup-proxy v-model="toggleCopy">
      <q-table
        flat dense
        class="bg-white"
        :data="data"
        :loading="loading"
        :columns="columns"
        :row-key="valueField"
        separator="cell"
        :selection="selection"
        :selected.sync="selected"
        :pagination.sync="pagination"
        :rows-per-page-options="[3, 5, 10]"
        no-data-label="暂无数据"
        table-class="h-custom"
        @request="listGet"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th>
              <q-checkbox :disable="disable" indeterminate-value="some" dense v-model="props.selected" />
            </q-th>
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              {{ col.label }}
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td width="56">
              <q-checkbox :disable="disable" dense v-model="props.selected" />
            </q-td>
            <q-td v-for="col in columns" :key="col.name" :props="props">{{ props.row[col.name] }}</q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="props">
          <q-pagination
            v-model="pagination.page"
            color="light-blue"
            :max-pages="5"
            :max="pages"
            :boundaryLinks="true"
            :directionLinks="true"
          />
          共 {{ total }} 条
        </template>
        <template v-slot:top-right="props">
          <div class="row justify-between items-center">
            <q-input v-model="searchForm.val" dense />
            <q-select
              dense
              v-model="searchForm.key"
              options-dense
              emit-value
              map-options
              :options="columns"
              option-value="name"
            />
            <div class="q-gutter-sm q-ml-sm">
              <q-btn color="light-blue" dense label="查询" size="sm"/>
              <q-btn color="secondary" dense label="重置" size="sm"/>
            </div>
          </div>
        </template>
      </q-table>
    </q-popup-proxy>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  props: {
    fieldName: {
      required: true,
      type: String
    },
    required: {
      default: false,
      type: Boolean
    },
    error: {
      default: false,
      type: Boolean
    },
    toggle: {
      default: false,
      type: Boolean
    },
    selection: {
      default: 'single',
      type: String
    },
    emitValue: {
      default: false,
      type: Boolean
    },
    valueField: {
      default: 'id'
    },
    labelField: {
      default: 'name'
    },
    value: {
      default: ''
    },
    label: {
      default: ''
    },
    url: {
      required: true,
      type: String
    },
    columns: {
      default () {
        return [
          { name: 'name', required: true, label: '名称', align: 'left', field: 'name', sortable: true },
          { name: 'code', required: true, label: '编码', align: 'left', field: 'code', sortable: true },
          { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
        ]
      },
      type: Array
    },
    disable: {
      default: false,
      type: Boolean
    },
    query: {
      type: Object
    }
  },
  data () {
    return {
      toggleCopy: this.toggle,
      errorCopy: this.error,
      valueCopy: this.value,
      labelCopy: this.label,
      // 内置参数
      data: [],
      total: 0,
      loading: false,
      selected: [],
      pagination: {
        page: 1,
        rowsPerPage: 8,
        rowsNumber: 8,
        sortBy: '',
        descending: Boolean
      },
      searchForm: {
        key: 'name',
        val: ''
      }
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({ pagination: this.pagination })
    },
    error (error) {
      this.errorCopy = error
    },
    toggleCopy (toggleCopy) {
      if (toggleCopy) {
        if (this.required) {
          this.errorCopy = false
        }
        this.listGet({ pagination: this.pagination })
      } else {
        this.selectedConfirm()
      }
    },
    selected (selected) {
    },
    value (value) {
      this.valueCopy = value
    }
  },
  methods: {
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination
      this.loading = true
      await this.$api({
        method: 'post',
        url: this.url,
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...this.query
        },
        emulateJSON: true,
        successCallback: ({ data }) => {
          // 回显
          let selectedArr = this.selected
          if (this.value !== '') {
            let vS = this.value + ''
            vS.split(',').forEach(v => {
              data.list.forEach(d => {
                if (v + '' === d[this.valueField] + '') {
                  selectedArr.push(d)
                }
              })
            })
          }
          this.loading = false
          this.selected = _.uniqBy(selectedArr, this.valueField)
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    selectedConfirm () {
      if (this.emitValue) {
        let v = [], l = []
        this.selected.forEach(s => {
          v.push(s[this.valueField])
          l.push(s[this.labelField])
        })
        this.labelCopy = l.join(',')
        if (this.required && !this.labelCopy) {
          this.errorCopy = true
        }
        if (this.required) {
          this.$emit('select', v, this.errorCopy)
        } else {
          this.$emit('select', v)
        }
      } else {
        // TODO: emit value object
        let l = []
        this.selected.forEach(s => {
          l.push(s[this.labelField])
        })
        this.labelCopy = l.join(',')
        this.$emit('select', this.selected)
      }
    }
  }
}
</script>
